using System;
using System.ComponentModel;
using System.Threading.Tasks;
using Avalonia.Threading;
using CommunityToolkit.Mvvm.ComponentModel;
using Eremex.AvaloniaUI.Controls.Editors;
using Prism.Commands;
using RoboDk.API;
using RoboDk.API.Model;

namespace JMCOM.Components.EpsonRobot
{
    public class RobotViewModel : BindableBase
    {
        private readonly IRoboDK _rdk = new RoboDK(); // 接入 RoboDK
        private IItem? _robot; 
        public IRegionManager RobotRegionManager { get; set; }
       
        public RobotViewModel( )
        {
           

        }
        public RobotViewModel(IRegionManager regionManager)
        {
            RobotRegionManager = regionManager;
             

        }

        private string _roboDKStatus = "未连接";
        public string RoboDKStatus
        {
            get => _roboDKStatus;
            set => SetProperty(ref _roboDKStatus, value);
        }

        private string _robotStatus = "";
        public string RobotStatus
        {
            get => _robotStatus;
            set => SetProperty(ref _robotStatus, value);
        }

        public string TargetX { get; set; } = "0";
        public string TargetY { get; set; } = "0";
        public string TargetZ { get; set; } = "0";

        // public DelegateCommand ConnectRoboDKCommand => new DelegateCommand(ConnectRoboDK);
        // public DelegateCommand StartCommand => new DelegateCommand(StartRobot, CanOperateRobot).ObservesProperty(() => _robot);
        // public DelegateCommand StopCommand => new DelegateCommand(StopRobot, CanOperateRobot).ObservesProperty(() => _robot);
        // public DelegateCommand ResetCommand => new DelegateCommand(ResetRobot, CanOperateRobot).ObservesProperty(() => _robot);
        // public DelegateCommand EmergencyStopCommand => new DelegateCommand(EmergencyStop, CanOperateRobot).ObservesProperty(() => _robot);
        // public DelegateCommand MoveJCommand => new DelegateCommand(async () => await MoveJAsync()).ObservesProperty(() => _robot);

        private bool CanOperateRobot()
        {
            return _robot != null && _robot.Valid();
        }

        private void ConnectRoboDK()
        {
            Task.Run(() =>
            {
                try
                {
                    // 确保 RDK 可用并已连接
                    if (_rdk == null)
                    {
                        UpdateStatus("RoboDK 未实例化");
                        return;
                    }

                    if (!_rdk.Connected())
                    {
                        var ok = _rdk.Connect(); // 默认连接尝试
                        if (!ok)
                        {
                            UpdateStatus("连接 RoboDK 失败");
                            return;
                        }
                    }

                    UpdateStatus("RoboDK 已连接");

                    // 让用户选择机器人（会弹出选择对话）
                    var picked = _rdk.ItemUserPick("Select a robot", ItemType.Robot);
                    if (picked == null || !picked.Valid())
                    {
                        UpdateStatus("未选择机器人或机器人不可用");
                        return;
                    }

                    // 保存机器人引用并创建独立链接（同示例）
                    _robot = picked;
                    _robot.NewLink();

                    UpdateStatus($"使用机器人: {_robot.Name()}");
                }
                catch (Exception ex)
                {
                    UpdateStatus("连接出错: " + ex.Message);
                }
            });
        }

        private void StartRobot()
        {
            if (!CanOperateRobot()) return;
            try
            {
                _robot.RunCode("START");
                UpdateRobotStatus("已发送 START");
            }
            catch (Exception ex)
            {
                UpdateRobotStatus("Start 失败: " + ex.Message);
            }
        }

        private void StopRobot()
        {
            if (!CanOperateRobot()) return;
            try
            {
                _robot.RunCode("STOP");
                UpdateRobotStatus("已发送 STOP");
            }
            catch (Exception ex)
            {
                UpdateRobotStatus("Stop 失败: " + ex.Message);
            }
        }

        private void ResetRobot()
        {
            if (!CanOperateRobot()) return;
            try
            {
                _robot.RunCode("RESET");
                UpdateRobotStatus("已发送 RESET");
            }
            catch (Exception ex)
            {
                UpdateRobotStatus("Reset 失败: " + ex.Message);
            }
        }

        private void EmergencyStop()
        {
            if (!CanOperateRobot()) return;
            try
            {
                _robot.RunCode("EMERGENCY_STOP");
                UpdateRobotStatus("已发送 EMERGENCY_STOP");
            }
            catch (Exception ex)
            {
                UpdateRobotStatus("EmergencyStop 失败: " + ex.Message);
            }
        }

        private async Task MoveJAsync()
        {
            if (!CanOperateRobot()) return;

            await Task.Run(() =>
            {
                try
                {
                    // 解析输入
                    var x = double.Parse(TargetX);
                    var y = double.Parse(TargetY);
                    var z = double.Parse(TargetZ);

                    // 优先使用站点中保存的 Target（如果存在名为 WorkPoint1）
                    var wp = _rdk.GetItemByName("WorkPoint1", ItemType.Target);
                    if (wp != null && wp.Valid())
                    {
                        // 设置速度与 rounding（zone）
                        _robot.SetSpeed(150);      // 示例：150 mm/s
                        _robot.SetRounding(5);     // 示例：允许圆角（等同 zone）
                        _robot.MoveJ(wp, true);    // MoveBlocking = true
                        UpdateRobotStatus($"已 MoveJ 到站点 WorkPoint1");
                        return;
                    }

                    // 否则用程式化构造的位姿：使用 FromTxyzRxyz（XYZ + RxRyRz）
                    // 这里只设置 XYZ，姿态采用 0,0,0（如需指定姿态请修改）
                    var xyzwpr = new double[] { x, y, z, 0.0, 0.0, 0.0 };
                    var pose = Mat.FromTxyzRxyz(xyzwpr);

                    _robot.SetSpeed(150);
                    _robot.SetRounding(5);
                    _robot.MoveJ(pose, true); // 阻塞移动
                    UpdateRobotStatus($"📍 已移动至 ({x}, {y}, {z})");
                }
                catch (Exception ex)
                {
                    UpdateRobotStatus("MoveJ 失败: " + ex.Message);
                }
            });
        }

        // 帮助方法：通过 Avalonia Dispatcher 回写 UI 字段
        private void UpdateStatus(string text)
        {
            Dispatcher.UIThread.Post(() => RoboDKStatus = text);
        }

        private void UpdateRobotStatus(string text)
        {
            Dispatcher.UIThread.Post(() => RobotStatus = text);
        }
    }
}
